package com.zan.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.zan.service.OrderService;
import com.zan.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    /**
     * 回调接口: 当用户支付成功之后，微信支付平台就会请求这个接口，将支付状态的数据传递过来
     */
    @RequestMapping("/callback")
    public String paySuccess(HttpServletRequest request) throws Exception {
//        System.out.println("----------callback");
        //1.接收微信支付平台传递的数据（使用request的输入流来接收） 【接收过来是xml结构】
        ServletInputStream inputStream = request.getInputStream();
        byte[] bs = new byte[1024];
        int len = -1;
        StringBuilder builder = new StringBuilder();
        while((len = inputStream.read(bs)) != -1) {
            builder.append(new String(bs, 0, len));
        }
        String s = builder.toString();
        //使用util类将接收到的数据转换成map
        Map<String, String> map = WXPayUtil.xmlToMap(s);

        if (map != null && "success".equalsIgnoreCase(map.get("result_code"))) {
            //支付成功
            //2.修改订单状态为"待发货/已支付"
            String oid = map.get("out_trade_no");
            int i = orderService.updateOrderStatus(oid, "2");
            if (i > 0) {
                //3.通过websocket连接，向前端推送消息
                WebSocketServer.sendMsg(oid, "1");

                //4.响应微信支付平台
                HashMap<String, String> resp = new HashMap<>();
                resp.put("return_code", "success");
                resp.put("return_msg", "OK");
                resp.put("app_id", map.get("appid"));
                resp.put("result_code", "success");

                return WXPayUtil.mapToXml(resp);
            }
        }
        return null;
    }
}
